package org.huangxiaozhe.adventure;

import org.huangxiaozhe.adventure.common.ConstantUtil;

import com.triplefstudio.adventure.R;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 
 * ����Ϸ����
 *
 */
public class GameView extends SurfaceView implements SurfaceHolder.Callback{
	
	private PlayActivity activity;
	private TutorialThread thread;//ˢ֡���߳�
	GameViewBackGroundThread gameThread;//���������߳�
	MoveThread moveThread;//�ƶ�������߳� 
	
	Pig pig;		//�ҷ��ɻ� 
	Road road;		//·��
	Tools tools;		//��ť����
	
	boolean init = false;
	int backGroundIX = 0;//����ͼ��x���
	int i = 0;//����ͼ������
	//int ScreenWidth = 0;
	//int ScreenHeigth = 0;
	//float ScreenLength = 0;
	
	String fps = "FPS: N/A";		//����֡�����ַ�
	
	Bitmap battleback;//�����Ĵ�ͼԪ
	Bitmap[] battlebacks = new Bitmap[ConstantUtil.pictureCount];//װ�ָ��Ժ��ͼƬ
	Paint paint;	//����
	public boolean canStart = true;
	public boolean canStop = true;
	
	public GameView(PlayActivity activity) {//������ 
		super(activity);
		this.activity = activity;//activity������
		
        getHolder().addCallback(this);//ע��ӿ�
        prepareThread();
    }
	
	public void prepareThread(){
        this.thread = new TutorialThread(getHolder(), this);//��ʼ��ˢ֡�߳�
        this.gameThread = new GameViewBackGroundThread(this);//��ʼ�����������߳�
        this.moveThread = new MoveThread(this);
	}
	
	public void initResource(){//��ʼ������ͼƬ
        
		paint = new Paint();
		paint.setColor(Color.BLACK);
		paint.setAntiAlias(true);
		battleback = BitmapFactory.decodeResource(getResources(), R.drawable.background);//�󱳾�ͼƬ
		Bitmap temp;
		for(int i=0; i<battlebacks.length; i++){//�г�СͼƬ
			temp = Bitmap.createBitmap(battleback, ConstantUtil.pictureWidth*i, 0, ConstantUtil.pictureWidth, ConstantUtil.pictureHeight);
			battlebacks[i] = Bitmap.createScaledBitmap(temp, (int)(ConstantUtil.screenLength + 0.5), ConstantUtil.screenHeight, false);
		}
		battleback = null;//�ͷŵ���ͼ
		
	    pig = new Pig(ConstantUtil.pigX, ConstantUtil.pigY, 0, ConstantUtil.life, this);//��ʼ���ҷ��ɻ� 
	    road = new Road(ConstantUtil.screenHeight * 7 / 8, this);
	    tools = new Tools(this);
	}
	
	public void onDraw(Canvas canvas){//�Լ�д�Ļ��Ʒ���,������д��
		if(!init)
		{
		    initResource();//��ʼ������ͼƬ
			init = true;
			postInvalidate();
		}
		
		//����������z��ģ��󻭵ĻḲ��ǰ�滭��
		int backGroundIX = this.backGroundIX;
		int i = this.i;
		
		//���i��������
		if(backGroundIX>0){
			int n=(backGroundIX/(int)ConstantUtil.screenLength)+((backGroundIX%(int)ConstantUtil.screenLength==0)?0:1);//����i�����м���ͼ
			for(int j=1; j<=n; j++){
				canvas.drawBitmap(
			      battlebacks[(i - j +  ConstantUtil.pictureCount) % ConstantUtil.pictureCount], 
			      backGroundIX-ConstantUtil.screenLength * j, 
			      ConstantUtil.top, 
			      paint
			     );
			}
		}

		//���i�Լ�
		canvas.drawBitmap(battlebacks[i], backGroundIX, ConstantUtil.top, paint);
		
		//���i�Ҳ������
		if(backGroundIX<ConstantUtil.screenWidth - ConstantUtil.screenLength){
			int k=ConstantUtil.screenWidth - (backGroundIX + (int)ConstantUtil.screenLength);
			int n=(k/(int)ConstantUtil.screenLength)+((k%(int)ConstantUtil.screenLength == 0)?0:1);//����i�����м���ͼ
			for(int j=1;j<=n;j++){
				canvas.drawBitmap(
						battlebacks[(i+j)%ConstantUtil.pictureCount], 
						backGroundIX+ConstantUtil.screenLength * j, 
						ConstantUtil.top, 
						paint
				);
			}
		}
		
		//���ƹ�����İ�ť
		tools.draw(canvas);
		//���Ƶ�ǰ·��
		road.draw(canvas);
		//���Ʒ���
		pig.draw(canvas);
		
		//����֡�����ַ�
		paint.setTextSize(ConstantUtil.screenHeight/18);
		canvas.drawText(fps, 15, ConstantUtil.screenHeight/18, paint);
		
		
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		Log.d(ConstantUtil.tag, "w:" + w + " h:" + h);
		ConstantUtil.screenWidth = w;
		ConstantUtil.screenHeight = h;
		ConstantUtil.screenLength = w / 9;
		ConstantUtil.pigX = w / 10;
		ConstantUtil.pigY = h * 4 / 5 - ConstantUtil.pigHeight;
		super.onSizeChanged(w, h, oldw, oldh);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	
	}
	
	public void surfaceCreated(SurfaceHolder holder) {//����ʱ������Ӧ���
		Log.d(ConstantUtil.tag, "surfaceCreated:" + thread.getState().name());
		thread.setFlag(true);//����ˢ֡�߳�
		gameThread.setFlag(true);
		moveThread.setFlag(true);
		thread.start();
		gameThread.start();//�������������߳�
		moveThread.start();//���������ƶ�����ƶ��߳�
	}
	
	public void surfaceDestroyed(SurfaceHolder holder) {//�ݻ�ʱ�ͷ���Ӧ���
		Log.d(ConstantUtil.tag, "surfaceDestroyed:" + thread.getState().name());
		boolean retry = true;
		thread.setFlag(false);
		gameThread.setFlag(false);
		moveThread.setFlag(false);
        while (retry) {
            try {
            	thread.join();
                gameThread.join();
                moveThread.join();
                retry = false;
            } 
            catch (InterruptedException e) {//���ϵ�ѭ����ֱ��ˢ֡�߳̽���
            }
        }
        
        Log.d(ConstantUtil.tag, "After surfaceDestroyed:" + thread.getState().name());
	}
	
	//��Ϸ�н��濪ʼ�ƶ�
	public void Start(){
		if(canStart){
			gameThread.Start();
	    	road.Start();
		}
	}
	
	//��Ϸ�н���ֹͣ�ƶ�
	public void Stop(){
		if(canStop){
			gameThread.Stop();
			road.Stop();
		}
	}
	
	class TutorialThread extends Thread{//ˢ֡�߳�
		private int count=0;		//��¼֡��ñ������ڼ���֡����
		private long start = System.nanoTime();	//��¼��ʼʱ�䣬�ñ������ڼ���֡����
		
		private int sleepSpan = 38;//˯�ߵĺ����� 
		private SurfaceHolder surfaceHolder;
		private GameView gameView;
		public boolean flag = false;
        public TutorialThread(SurfaceHolder surfaceHolder, GameView gameView) {//������
            this.surfaceHolder = surfaceHolder;
            this.gameView = gameView;
        }

        public void setFlag(boolean flag) {//����ѭ�����λ
        	this.flag = flag;
        }
        
		@Override
		public void run() {
			Canvas c;
            while (flag) {
                c = null;
                try {
                	// ��������������ڴ�Ҫ��Ƚϸߵ�����£��������ҪΪnull
                    c = this.surfaceHolder.lockCanvas(null);
                    synchronized (this.surfaceHolder) {
                    	gameView.onDraw(c);//����
                    }
                } finally {
                    if (c != null) {
                    	//������Ļ��ʾ����
                        this.surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
                
                this.count++;
        		if(count == 30){						//������20֡
        			count = 0;							//��ռ�����
        			long tempStamp = System.nanoTime();	//��ȡ��ǰʱ��
        			long span = tempStamp - start;		//��ȡʱ����
        			start = tempStamp;					//Ϊstart���¸�ֵ
        			 fps = "FPS: " + Math.round(100000000000.0/span*30)/100.0;//����֡����
        		}
                try{
                	Thread.sleep(sleepSpan);//˯��ָ��������
                }
                catch(Exception e){
                	e.printStackTrace();//��ӡ��ջ��Ϣ
                }
            }
		}
	}

	public void Move() {
		road.Move();
		pig.Move();
	}
	
	public void moveFinger(float x, float y) {
		if(pig.currentTool == 1){
			pig.moveFinger(x,y);
		}
	}

	public void downFinger(float x, float y) {
		if(pig.currentTool == 1){
			pig.downFinger(x, y);
		}
	}

	public void upFinger(float x, float y) {
		if(pig.currentTool == 1){
			pig.upFinger(x, y);
		}
	}
}